import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { 
  Plus, 
  Edit2, 
  Trash2, 
  FolderOpen, 
  Play,
  FileText 
} from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import toast from 'react-hot-toast'
import { suiteApi } from '../services/api'
import SuiteEditModal from './SuiteEditModal'

const SuiteManager = ({ onItemSelect }) => {
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingSuite, setEditingSuite] = useState(null)
  const [selectedSuites, setSelectedSuites] = useState(new Set())
  const queryClient = useQueryClient()

  // 获取套件列表
  const { data: suites = [], isLoading } = useQuery({
    queryKey: ['suites'],
    queryFn: () => suiteApi.getSuites().then(res => res.data)
  })

  // 删除套件
  const deleteSuiteMutation = useMutation({
    mutationFn: suiteApi.deleteSuite,
    onSuccess: () => {
      queryClient.invalidateQueries(['suites'])
      toast.success('套件已删除')
    },
    onError: (error) => {
      toast.error(`删除失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  const handleSuiteSelect = (suite) => {
    onItemSelect({
      ...suite,
      type: 'suite'
    })
  }

  const handleEdit = (suite) => {
    setEditingSuite(suite)
  }

  const handleDelete = async (filename) => {
    if (confirm('确定要删除这个套件吗？此操作无法撤销。')) {
      await deleteSuiteMutation.mutateAsync(filename)
    }
  }

  const handleBatchDelete = async () => {
    if (selectedSuites.size === 0) return
    
    if (confirm(`确定要删除选中的 ${selectedSuites.size} 个套件吗？此操作无法撤销。`)) {
      const promises = Array.from(selectedSuites).map(filename => 
        deleteSuiteMutation.mutateAsync(filename)
      )
      
      try {
        await Promise.all(promises)
        setSelectedSuites(new Set())
        toast.success(`已删除 ${selectedSuites.size} 个套件`)
      } catch (error) {
        toast.error('批量删除时出现错误')
      }
    }
  }

  const toggleSuiteSelection = (filename) => {
    setSelectedSuites(prev => {
      const newSet = new Set(prev)
      if (newSet.has(filename)) {
        newSet.delete(filename)
      } else {
        newSet.add(filename)
      }
      return newSet
    })
  }

  if (isLoading) {
    return (
      <div className="p-6 h-full flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600 mx-auto"></div>
          <p className="text-sm text-gray-500 mt-2">加载套件列表中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col">
      {/* 头部工具栏 */}
      <div className="p-6 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">套件管理</h2>
            <p className="text-sm text-gray-500 mt-1">
              管理和编辑测试套件 ({suites.length} 个套件)
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            {selectedSuites.size > 0 && (
              <button
                onClick={handleBatchDelete}
                className="text-red-600 hover:text-red-800 text-sm flex items-center"
              >
                <Trash2 className="w-4 h-4 mr-1" />
                删除选中 ({selectedSuites.size})
              </button>
            )}
            
            <button
              onClick={() => setShowCreateModal(true)}
              className="btn-primary"
            >
              <Plus className="w-4 h-4 mr-2" />
              创建套件
            </button>
          </div>
        </div>
      </div>

      {/* 套件列表 */}
      <div className="flex-1 overflow-y-auto p-6">
        {suites.length === 0 ? (
          <div className="h-full flex items-center justify-center">
            <div className="text-center">
              <FolderOpen className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-500 mb-2">
                暂无套件
              </h3>
              <p className="text-sm text-gray-400 mb-4">
                创建测试套件来批量执行多个任务
              </p>
              <button
                onClick={() => setShowCreateModal(true)}
                className="btn-primary"
              >
                <Plus className="w-4 h-4 mr-2" />
                创建套件
              </button>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <AnimatePresence>
              {suites.map((suite) => (
                <motion.div
                  key={suite.filename}
                  layout
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.9 }}
                  className="card hover:shadow-md transition-all cursor-pointer group"
                >
                  <div className="card-content">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          checked={selectedSuites.has(suite.filename)}
                          onChange={() => toggleSuiteSelection(suite.filename)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                          onClick={e => e.stopPropagation()}
                        />
                        <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                      </div>
                      
                      <div className="opacity-0 group-hover:opacity-100 transition-opacity">
                        <div className="flex items-center space-x-1">
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              handleSuiteSelect(suite)
                            }}
                            className="p-1 hover:bg-gray-100 rounded"
                            title="选择并执行"
                          >
                            <Play className="w-4 h-4 text-green-600" />
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              handleEdit(suite)
                            }}
                            className="p-1 hover:bg-gray-100 rounded"
                            title="编辑"
                          >
                            <Edit2 className="w-4 h-4 text-blue-600" />
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation()
                              handleDelete(suite.filename)
                            }}
                            className="p-1 hover:bg-gray-100 rounded"
                            title="删除"
                          >
                            <Trash2 className="w-4 h-4 text-red-600" />
                          </button>
                        </div>
                      </div>
                    </div>
                    
                    <div onClick={() => handleSuiteSelect(suite)}>
                      <h3 className="font-semibold text-gray-900 mb-2 line-clamp-2">
                        {suite.name}
                      </h3>
                      
                      <p className="text-sm text-gray-500 mb-3 line-clamp-3">
                        {suite.description || '暂无描述'}
                      </p>
                      
                      <div className="flex items-center justify-between text-xs text-gray-400">
                        <span className="flex items-center">
                          <FileText className="w-3 h-3 mr-1" />
                          {suite.filename}
                        </span>
                        <span>套件</span>
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        )}
      </div>

      {/* 创建/编辑模态框 */}
      <AnimatePresence>
        {(showCreateModal || editingSuite) && (
          <SuiteEditModal
            suite={editingSuite}
            isOpen={showCreateModal || !!editingSuite}
            onClose={() => {
              setShowCreateModal(false)
              setEditingSuite(null)
            }}
            onSuccess={() => {
              queryClient.invalidateQueries(['suites'])
              setShowCreateModal(false)
              setEditingSuite(null)
            }}
          />
        )}
      </AnimatePresence>
    </div>
  )
}

export default SuiteManager